/********************************************************************
	Created:	2013/02/06  19:37
	Filename: 	MyHandler.cpp
	Author:		rrrfff
	Url:	    http://blog.csdn.net/rrrfff
*********************************************************************/
#include "MyStruct.h"
using namespace System::Security::Cryptography;

//-------------------------------------------------------------------------

#define ResponseWrite(Content)       this->Send(Content, sizeof(Content) - sizeof(char));

//-------------------------------------------------------------------------

void RequestInfo::DoCoreTask()
{
	ResponseWrite("220 lexunchina2014.tk RLib Server\n\n");

	if(!this->RecvLine()) return;
	if (strstr(this->RequestText, "HELO") == this->RequestText)
	{
		ResponseWrite("250 OK\n\n");
	} //if
	else if (strstr(this->RequestText, "EHLO") == this->RequestText)
	{
		ResponseWrite("250-lexunchina2014.tk\n\n");
		ResponseWrite("250-AUTH LOGIN PLAIN\n\n");
		ResponseWrite("250-AUTH=LOGIN\n\n");
		ResponseWrite("250 8BITMIME\n\n");
	}
	else return;

	
	if(!this->RecvLine()) return;//MAIL FROM

	ResponseWrite("250 OK\n\n");

	if(!this->RecvLine()) return;//RCPT TO

	ResponseWrite("250 OK\n\n");

	if(!this->RecvLine()) return;//DATA

	ResponseWrite("354 End data with .\n\n");

	BufferedStream data;
	int size = 0;
again:
	if(!this->RecvLine(&size)) return;//DATA CONTENT
	data.Write(this->RequestText, size);
	if(strstr(LPSTR(data.GetObjectData()), "\n.") == nullptr)
	{
		goto again;
	}

	ResponseWrite("250 OK\n\n");

	if(!this->RecvLine()) return;//QUIT

	ResponseWrite("221 Bye\n\n");

	LPSTR pdata = strstr((LPSTR)data.GetObjectData(), "\r\n\r\n");
	if (pdata != nullptr)
	{
		String page = String(pdata).Trim().TrimEnd(T('.')).TrimEnd();
		LPVOID pdata_encoded = Base64::DecodeBytes(page.ToMultiByte(), page.GetMultiByteSize(), &size);
		if (pdata_encoded != nullptr)
		{
			MemoryStream *pdata_decoded_stream = Text::Encoder::ToCurrentEncoding(
				Text::UnknownEncoding, &UnmanagedMemoryStream(pdata_encoded, size, size), 0, false);
			if (pdata_decoded_stream != nullptr)
			{
				page = (LPCTSTR)pdata_decoded_stream->GetObjectData();
#define _MY
#ifdef _MY

#endif // _MY
				delete pdata_decoded_stream;
			} //if
			Base64::Collect(pdata_encoded);
		} //if
	} //if
}